package com.ygqh.baby.controller.mobile;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgPrepayBookRecord;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserOpen;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人中心
 * 
 * @author guohao
 *
 */
@Controller
@RequestMapping("/mobile/userCentre")
public class YgUserCentreController extends BaseController {
	@Autowired
	private YgUserService userService;
	@Autowired
	private YgOrderService orderService;
	@Autowired
	private YgProductCommentService productCommentService;
	@Autowired
	private YgMessageService ygMessageService;
	@Autowired
	private DocumentConstant documentConstant;
	@Value("${promotion.link}")
	protected String promotionLink;
	@Autowired
	private FileService fileService;
	@Autowired
	private YgUserOpenService ygUserOpenService;
	@Autowired
	private RedisDao redisDao;
	@Value("${image.domain}")
	private String domain;
	@Autowired
	private YgCouponDetailService ygCouponDetailService;
	@Autowired
	private YgUserMemberService ygUserMemberService;
	@Autowired
	private YgPrepayBookRecordService ygPrepayBookRecordService;

	/**
	 * 获取用户信息
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findHeadUrlByUserName", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findHeadUrlByUserName(String userName, String callback) {
		YgUser user = userService.findByUserName(userName);
		YgUser user1 = SessionUtil.getCurrentUser();
		Map<String, String> map = new HashMap<>();
		map.put("tiaozhanzhe", user1.getHeadImageUrl());
		map.put("beitiaozhanzhe", user.getHeadImageUrl());
		JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}

	/**
	 * 获取用户信息
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findUserInfo", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findUserInfo(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		YgUserModel userInfo = userService.findUserInfo(user.getId());
		String birthday = DateConvertUtils.getBabyBirthday(userInfo.getBabyBirthday());
		userInfo.setbBirthday(birthday);
//		if (userInfo.getUserType().equals(UserType.UserAgent)) {
//			YgAgentInviteRecord agentInviteRecord = ygAgentInviteRecordService.findValidByReceiveUserId(user.getId());
//			userInfo.setMemberStartTime(agentInviteRecord.getReceiveTime());
//			userInfo.setMemberEndTime(agentInviteRecord.getExpireTime());
//		}
		JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, userInfo));
		return json;
	}

	/**
	 * 更新用户信息
	 * 
	 * @param userLogo
	 * @param nickName
	 * @param babyGender
	 * @param babyBirthday
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "updateUserInfo", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject updateUserInfo(String userLogo, String nickName, Integer babyGender, Date babyBirthday, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		JSONPObject json = null;
		if (StringUtil.isNotBlank(nickName)) {
			if (nickName.length() >= 50) {
				return new JSONPObject(callback, Message.error("昵称超长", nickName));
			}
		}
		int row = userService.updateUserInfo(user.getId(), userLogo, nickName, babyGender, babyBirthday);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, row));
		return json;
	}

	/**
	 * 获取不同状态下订单数量
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findCountByOrderStatus", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findCountByOrderStatus(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		List<Map<String, Object>> maps = orderService.findCountByOrderStatus(user.getId());
		int unCommentComplete = orderService.countUnCommentComplete(user.getId());
		for (Map<String, Object> map : maps) {
			if (map.get("orderStatus").equals("TradeSuccess")) {
				map.put("amount", unCommentComplete);
			}
		}
		JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, maps));
		return json;
	}

	/**
	 * 个人中心首页是否显示红点
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "isShowForMe", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject isShowForMe(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		Map<String, Object> map = new HashMap<String, Object>();
		int countMsg = ygMessageService.findUnReadCount(user.getId());
		// TODO 提成
		int countTicheng = 0;
		Boolean isShowForMsg = false;
		Boolean isShowForTiCheng = false;
		if (countMsg > 0) {
			isShowForMsg = true;
		}
		if (countTicheng > 0) {
			isShowForTiCheng = true;
		}
		map.put("message", isShowForMsg);
		map.put("ticheng", isShowForTiCheng);
		JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}

	/**
	 * 个人中心获取订单列表
	 * 
	 * @param queryInfo
	 * @param orderStatus
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findMyOrderList", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findMyOrderList(QueryInfo queryInfo, OrderStatus orderStatus, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgOrderModel> orderList = orderService.findOrderList(queryInfo, user.getId(), orderStatus);
		JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, orderList));
		return json;
	}

	/**
	 * 个人中心 由订单列表进入某一订单详情页
	 * 
	 * @param orderId
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findOrderInfo", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findOrderInfo(Long orderId, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		YgOrderInfoModel model = orderService.findOrderInfo(orderId, user.getId());
		JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));
		return json;
	}

	@RequestMapping(value = "findOrderInfoKF", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findOrderInfoKF(Long orderId, String callback) {
		YgOrderInfoModel model = orderService.findOrderInfo(orderId, null);
		JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));
		return json;
	}

	/**
	 * 获取订单物流信息
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "getLogisticsInfo")
	@ResponseBody
	public JSONPObject getLogisticsInfo(String expCode, String expNo, String callback) {

		Message msg = orderService.getLogisticsInfo(expCode, expNo);

		JSONPObject json = new JSONPObject(callback, msg);
		return json;
	}

	/**
	 * 获取该订单所有商品评论情况
	 * 
	 * @param orderId
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findWaitingComment", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findWaitingComment(Long orderId, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgOrder4CommentModel> models = orderService.findWaitingComment(orderId, user.getId());
		JSONPObject json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, models));
		return json;
	}

	/**
	 * 提交商品评论
	 * 
	 * @param orderId
	 * @param productId
	 * @param skuId
	 * @param content
	 * @param imagesUrls
	 * @param commentTags
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "commentOrderItem", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject commentOrderItem(Long orderId, Long productId, Long skuId, String content, String imagesUrls, CommentTag[] commentTags,
										Long couponBatchId, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		JSONPObject json;
		if (content.length() >= 300) {
			return new JSONPObject(callback, Message.error("评论内容超长", content));
		}
		Long couponDetailId = 0L;
		Boolean isFirstComment = true;
		Map<String, Long> map = orderService.orderIsComment(orderId);
		Long commentCount = map.get("commentCount");
		if (commentCount.intValue() > 0) {
			isFirstComment = false;
		}
		YgOrder order = orderService.findByOrderId(orderId);
		if (order.getUserId().intValue() == user.getId().intValue() &&
				isFirstComment) {
			try {
				Message msg = ygCouponDetailService.receiveIncreateCoupon(couponBatchId, user);
				couponDetailId = (Long) msg.getExtra();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		int row = productCommentService.commentOrderItem(orderId, user, productId, skuId, content, imagesUrls, commentTags, couponDetailId);

		json = new JSONPObject(callback, Message.success("评价成功", row));
		return json;
	}

	/**
	 * 成为推广员
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "becomeSeller", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject becomeSeller(@RequestParam(required = true) String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		int r = userService.becomeSeller(user.getId());
		JSONPObject json = new JSONPObject(callback, Message.success(r));
		return json;
	}

	/**
	 * 是否是推广员
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "isSeller", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject isSeller(@RequestParam(required = true) String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		user = userService.findById(user.getId());
		Boolean r = true;
		if (user.getIsSeller() == null || user.getIsSeller() == false) {
			r = false;
		}
		JSONPObject json = new JSONPObject(callback, Message.success(r));
		return json;
	}

	@RequestMapping(value = "isNewCustom", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject isNewCustom(@RequestParam(required = true) String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		Boolean newCustom = userService.isNewCustom(user.getId());
		JSONPObject json = new JSONPObject(callback, Message.success(newCustom));
		return json;
	}

	/**
	 * 个人中心获取推荐用户
	 * 
	 * @param queryInfo
	 * @param orderStatus
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findRecommendUser", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findRecommendUser(QueryInfo queryInfo, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserRecommendModel> userRecommendList = null;
		if (UserType.Group.equals(user.getUserType())) {
			userRecommendList = userService.findUserRecommend(queryInfo, null, user.getGroupTag());
		} else {
			userRecommendList = userService.findUserRecommend(queryInfo, user.getSourceCode(), null);
		}
		JSONPObject json = new JSONPObject(callback, Message.success(userRecommendList));
		return json;
	}

	@SuppressWarnings("deprecation")
	@RequestMapping("getTGZYCodeUrl")
	@ResponseBody
	public JSONPObject getTGZYCodeUrl(String callback, String qrCodeName, HttpServletRequest request) throws UnsupportedEncodingException {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		String url = promotionLink + "?sourceCode=" + user.getSourceCode();
		String path = request.getRealPath("/");
		String realPath = path + "/TGZYCodeImage";
		String fileName = "TGZY" + user.getSourceCode() + ".jpg";
		String qtcodeUrl = "";
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			realPath = QRCodeUtil.encode(url, realPath, fileName);
			if (!StringUtil.isBlank(realPath)) {
				String ext = fileName.split("\\.")[1];
				String yunTupian = HttpUtil.saveImageToDisk(domain + "/default/" + qrCodeName + ".jpg", realPath);
				ImageUtils.pressImageMark(realPath, yunTupian, realPath, 0, 0, 1.0f);
				File file = new File(realPath);
				qtcodeUrl = fileService.uploadImage(file, new FileType[] { FileType.QrCode }, ext, true, request);
			}
		} catch (Exception e) {
			logger.debug("生成推广二维码失败.sourceCode = " + user.getSourceCode());
			e.printStackTrace();
		}
		// 生成推广短连接
		map.put("codeUrl", qtcodeUrl);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}

	@RequestMapping(value = "findScanInfo", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findScanInfo(String openId, Date startDate, Date endDate, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		if (StringUtil.isBlank(openId)) {
			openId = user.getOpenId();
		}
		Boolean received = this.isReceived(user.getId());
		List<YgUserOpen> list = ygUserOpenService.findScanCountByFromCode(new String[] { user.getUserName() }, startDate, endDate, openId);
		JSONPObject json = new JSONPObject(callback, Message.success(received + "", list));
		return json;
	}

	@RequestMapping(value = "receiveGift715", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject receiveGift715(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String set = redisDao.set("715ZHANHUI-" + user.getId(), "true", 0);
		return new JSONPObject(callback, Message.success(set));
	}

	private Boolean isReceived(Long userId) {
		String result = redisDao.get("715ZHANHUI-" + userId);
		if (StringUtil.isNotBlank(result)) {
			return true;
		}
		return false;
	}

	@RequestMapping(value = "getMapVipPrice", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject getMapVipPrice(String callback) {
		Map<String, BigDecimal> map = ygUserMemberService.getMapVipPrice();
		return new JSONPObject(callback, Message.success(map));
	}

	@RequestMapping(value = "findMyBookRecordList", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findMyBookRecordList(QueryInfo queryInfo, YgPrepayBookRecord.RecordStatus recordStatus, String callback) {
		List<ProductBookRecordModel> recordList = ygPrepayBookRecordService.findList(queryInfo, null, SessionUtil.getCurrentUser().getId(), recordStatus);
		Map<String, Object> extra = new HashMap<>();
		extra.put("recordList", recordList);
		extra.put("currentTimeStamp", DateConvertUtils.getDateStart(new Date()));
		return new JSONPObject(callback, Message.success(extra));
	}

	@RequestMapping(value = "findBookRecordInfo", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findBookRecordInfo(@RequestParam Long recordCode, String callback) {
		ProductBookRecordModel record = ygPrepayBookRecordService.findByRecordCode(recordCode);
		Map<String, Object> extra = new HashMap<>();
		extra.put("record", record);
		extra.put("currentTimeStamp", DateConvertUtils.getDateStart(new Date()));
		return new JSONPObject(callback, Message.success(extra));
	}

}
